﻿



import Request from '../../base/request.js?t=202511041006'
import Storage from '../../base/storage.js?t=202511041006'
import { dealTime, downloadfun,queryURLParams, IgetDeptList, getBrowserInfo, previewCom, popShowCom, isImageFile} from "../../base/utils.js?t=202511041006"
const Composition = (proxy) => {


    const data = reactive({
        messageTest: "",
        proxy: "",
        popTitle: "",
        cIndex: 1,
        previewInfo: {
            pdfurl: "",
            pdfOpen: false,
            previewShow: false,
            imgUrl: ""
        },
        uploadImg: {
            fileList: [

            ]
        },
        uinfo: {

        },
        formData: {
        
        },
        //IsValidList: [
        //    { label: "有效", value: true },
        //    { label: "无效", value: false },
        //],
        IsTrainingList: [
            { label: "是", value: true },
            { label: "否", value:false },
        ],
        levelList: [
            { label: '安全(剩余天数大于90天)', value: 1 },
            { label: '注意(剩余天数小于90天)', value: 2 },
            { label: '警告(剩余天数小于30天)', value: 3 },
            { label: '危险(剩余天数小于0天)', value: 4 },

        ],

        formRules: {
            DeviceTypeId: [
                { required: true, message: '请选择设备种类', trigger: 'change' }
            ],
            DeviceStatus: [
                { required: true, message: '请选择设备状态', trigger: 'change' }
            ],
            DeviceName: [
                { required: true, message: '请输入设备名称', trigger: 'change' }
            ],
            UseDepartment: [
                { required: true, message: '请输入使用部门', trigger: 'change' }
            ],
            //UseCertificationCode: [
            //    { required: true, message: '请输入使用证号', trigger: 'change' }
            //],
            InstallPlace: [
                { required: true, message: '请输入安装地点', trigger: 'change' }
            ],
            //ResponsibleDepartment: [
            //    { required: true, message: '请输入责任部门', trigger: 'change' }
            //],
            //ResponsibleEmployee: [
            //    { required: true, message: '请输入负责人', trigger: 'change' }
            //],
            //ResponsibleContact: [
            //    { required: true, message: '请输入负责人电话', trigger: 'change' }
            //],
            //OnSiteEmployee: [
            //    { required: true, message: '请输入现场负责人', trigger: 'change' }
            //],
            //OnSiteContact: [
            //    { required: true, message: '请输入现场负责人电话', trigger: 'change' }
            //],
        },
  
 

        tabList: [
 
        ],
        queryParams: {
            IsRepair: null,
            IsDanger: null
        },


        eqstatusList: [],
        eqtype1List: [],
        eqtype2List: [],
        eqtype3List: [],

        cIds:[],

        CertiTypeList:[],
        urlinfo: {},
        popType: null,
        uploadLock: false,
        opType: true,
        popShow: false,

        pagination: {
            total: 0,
            current: 1,
            pageSize: 20,
            loading: true,
            showTotal: total => `总共 ${total} 项`,
            defaultPageSize: 20,
            showSizeChanger: true, // 是否显示pagesize选择
            showQuickJumper: false, // 是否显示跳转窗
        },
        citem: {},
        deptList: [],
        columns: [
            {
                title: '序号',
                dataIndex: 'index',
                key: 'index',
                align: 'left',
                width: 60,
                fixed: 'left',
                customRender: ({ index }) => {
                    return (params.pagination.value.current - 1) * params.pagination.value.pageSize + index + 1
                },
            },

            {
                title: '设备状态',
                dataIndex: 'DeviceStatusName',
                key: 'DeviceStatusName',
                align: 'left',
            },
            {
                title: '剩余天数',
                dataIndex: 'Days',
                key: 'Days',
                align: 'left',
    
                customRender: ({ text }) => {
                    // 默认值处理
                    if (!text && text !== 0) text = 0;
                    const num = Number(text);

                    // 颜色规则定义（按顺序匹配）
                    const colorRules = [
                        { condition: num > 90, color: '#21b180' },
                        { condition: num > 30, color: '#e5c51a' },
                        { condition: num >= 0, color: '#ff562b' },
                        { condition: true, color: '#d92223' } // 默认兜底（即 num < 0）
                    ];

                    // 找到第一个满足条件的颜色
                    const matchedRule = colorRules.find(rule => rule.condition) || {};
                    const color = matchedRule.color || '#999';

                    const tag = h(antd.Tag, {
                        style: { color: '#fff', backgroundColor: color, borderColor: color }
                    }, { default: () => `${num}天` });

                    return tag;
                }
            },
            {
                title: '设备编码',
                dataIndex: 'DeviceNo',
                key: 'DeviceNo',
                align: 'left',
      
            },
            {
                title: '设备名称',
                dataIndex: 'DeviceName',
                key: 'DeviceName',
                align: 'left',
        
            },
            {
                title: '设备种类',
                dataIndex: 'DeviceTypeName',
                key: 'DeviceTypeId',
                align: 'left',
        
            },
            {
                title: '设备类别',
                dataIndex: 'DeviceCategoryName',
                key: 'DeviceCategory',
                align: 'left',
                width:120
     
            },
            {
                title: '安装地点',
                dataIndex: 'InstallPlace',
                key: 'InstallPlace',
                align: 'left',
          
            },
            {
                title: '使用部门',
                dataIndex: 'UseDepartment',
                key: 'UseDepartment',
                align: 'left',
   
                customRender: function ({ text }) {


                    let hdiv = () => h('div', {
                        style: `max-width: 600px;`
                    }, {
                        default: () => text
                    });
                    const pop = () => h(antd.Popover, {
                        title: '详情',
                        content: hdiv(),
                    }, () => [text.length > 12 ? text.slice(0, 12) + '...' : text]);

                    return h('div', {
                    }, { default: () => [pop()] })


                }

            },
   
            {
                title: '责任人',
                dataIndex: 'ResponsibleEmployee',
                key: 'ResponsibleEmployee',
                align: 'left',
                width: 100,
            },
            {
                title: '本次检验日期',
                dataIndex: 'LastCheckTime',
                key: 'LastCheckTime',
                align: 'left',
        
                customRender: function ({ text }) {
                    return text ? dealTime(text, 'YYYY-MM-DD') : '-'
                }
            },
            {
                title: '下次检验日期',
                dataIndex: 'NextCheckTime',
                key: 'NextCheckTime',
                align: 'left',
   
                customRender: function ({ text }) {
                    return text ? dealTime(text, 'YYYY-MM-DD') : '-'
                }
            },
            {
                title: '是否危险点',
                dataIndex: 'IsDanger',
                key: 'IsDanger',
                align: 'left',
                customRender: function ({ text }) {
                    let textc = h(antd.Tag, {
                        color: text == true ? "#1677ff" : "#9e9e9e",
                    }, { default: () => text ? '是' : '否' });
                    return textc
                }
     
            },
            {
                title: '责任部门',
                dataIndex: 'ResponsibleDepartment',
                key: 'ResponsibleDepartment',
                align: 'left',
    
                customRender: function ({ text }) {


                    let hdiv = () => h('div', {
                        style: `max-width: 600px;`
                    }, {
                        default: () => text
                    });
                    const pop = () => h(antd.Popover, {
                        title: '详情',
                        content: hdiv(),
                    }, () => [text.length > 12 ? text.slice(0, 12) + '...' : text]);

                    return h('div', {
                    }, { default: () => [pop()] })


                }
            },
            {
                title: '操作',
                key: 'action',
                align: 'left',
                width: 160,
                fixed: 'right',
                customRender: function ({ text, record, index, column }) {




                    const FDBtn = h(antd.Popconfirm, {
                        title: `提示：设备编码【${record.DeviceNo}】，删除后将无法恢复，请您确认。`,
                        onConfirm: () => methods.handleDelete(record),
                        size:'small'
                    }, { default: () => [delBtn] })

                    let detailBtn = h(antd.Button, {
                        type: "link",
                        onClick: () => methods.handleDetail(record),
                        size: 'small'
                    }, { default: () => '详情' })

                    let editBtn = h(antd.Button, {
                        type: "link",
                        onClick: () => methods.handleEdit(record),
                        size: 'small'
                    }, { default: () => '编辑' })


                    let delBtn = h(antd.Button, {
                        type: "link",
                        size: 'small',
                        danger:true
                    }, { default: () => '删除' })







                    return h(antd.Space, {

                    },
                        { default: () => [editBtn, FDBtn, detailBtn] }
                    );

                }
            },
        ],



        dataSource: [],


    })
    let params = toRefs(data)
    const methods = {
        //IGetCertiTypeList: () => {
        //    params.uploadLock.value = true
        //    Request({
        //        url: `/SafetyCertification/GetCertiTypeList`,
        //        method: 'post',
        //    }).then(res => {
        //        console.log(res, 'res')
        //        params.CertiTypeList.value = res.Data?.map(e => ({ label: e.TypeValue, value: e.Id }))
        //    }).finally(() => {
        //        params.uploadLock.value = false
        //    })
        //},

        //IGetTypeList: () => {
        //    params.uploadLock.value = true
        //    Request({
        //        url: `/SafetyCertification/GetTypeList`,
        //        method: 'post',
        //    }).then(res => {
        //        params.tabList.value = res.Data?.map(e => ({ label: e.TypeValue, value: e.Id }))
        //    }).finally(() => {
        //        params.uploadLock.value = false
        //    })
        //},
        handleReset: () => {
            params.queryParams.value = {
                IsDanger: null,
                IsRepair: null
            }
            methods.getTableList(true)
        },
        handleExport: () => {
            params.uploadLock.value = true
            Request({
                url: `/SpecialDevice/ExportSpecialDevice`,
                method: 'post',
                data: {
                    model: {
                        ...params.queryParams.value,
                    },
                    IdList: params.cIds.value
                }
            }).then(res => {
                if (!res.Data) {
                    return params.messageTest.value.info("获取下载地址失败")
                }
                let ss = res.Data
                const match = ss.split('/')[ss.split('/').length - 1].split('.')[0]
                console.log(match)
                if (match) {

                    downloadfun(match, res.Data)
                } else {
                    console.log('未匹配到文件名称')
                }



            }).finally(() => {
                params.uploadLock.value = false
            })
        },
        handleImport: (info, type) => {
            if (!params.uploadLock.value) {
                params.uploadLock.value = true
                let formData = new FormData();
                formData.append('file', info.file.originFileObj)
                formData.append('Type', params.cIndex.value)
                if (type == 0) {
                    Request({
                        url: `/SpecialDevice/ImportOldData`,
                        method: 'post',
                        data: formData
                    }).then(res => {
                        params.messageTest.value.success('导入成功');
                        methods.getTableList(true)
                        params.uploadLock.value = false

                    })
                } else {
                    Request({
                        url: `/SpecialDevice/ImportData`,
                        method: 'post',
                        data: formData
                    }).then(res => {
                        params.messageTest.value.success('导入成功');
                        methods.getTableList(true)
                        params.uploadLock.value = false
                    })
                }


            }
        },
        handleChange: (info) => {
            let subarrys = info.fileList.filter(e => !e.old).map(e => e.originFileObj)

            if (!params.uploadLock.value) {
                params.uploadLock.value = true
                let formData = new FormData();

                for (let e of subarrys) {
                    formData.append('file', e)
                }
                Request({
                    url: `/download/uploadfile?Path=SpecialDevice`,
                    method: 'post',
                    data: formData
                }).then(res => {
                    params.uploadImg.value.fileList = [
                        ...res.Data.map(e => {
                            const { FilePath, FileName } = e
                            e.url = FilePath
                            e.name = FileName
                            return e
                        }),
                        ...params.uploadImg.value.fileList.filter(e => e.FileId)
                    ]

                }).finally(() => {
                    params.uploadLock.value = false
                })

            }
        },

        rowSelection: {
            onChange: (selectedRowKeys, selectedRows) => {
                params.cIds.value = selectedRowKeys
            },
            getCheckboxProps: (record) => ({
            }),
        },
        getDeptList: () => {
            return new Promise(async (resolve, rej) => {
                params.deptList.value = await IgetDeptList(Request)
                if (params.deptList.value) {
                    resolve(1)
                }
            })


        },

        itemRender: (data, type) => {
            let uid = data.file.FileId

            var btnPreview = (e) => {
                let item = params.uploadImg.value.fileList.find(es => es.FileId == e)
                item.url = item.FilePath || item.url
                if (item.FileName.indexOf('.pdf') != -1) {
                    params.previewInfo.value.pdfUrl = item.url
                    params.previewInfo.value.pdfOpen = true
                } else {
                    params.previewInfo.value.imgUrl = item.url
                    params.previewInfo.value.previewShow = true
                }
            }
            var btnDownLoad = (e) => {
                let item = params.uploadImg.value.fileList.find(es => es.FileId == e)
                item.url = item.FilePath || item.url
                const { name, url } = item
                params.uploadLock.value = true
                downloadfun(name, url).finally(() => {
                    params.uploadLock.value = false
                })
            }
            var btnDelete = (e) => {
                const { FileId } = e.file
                if (FileId) {
                    params.uploadLock.value = true
                    methods.IDeleteFile(FileId).then(res => {
                        params.uploadImg.value.fileList = params.uploadImg.value.fileList.filter(e => e.FileId != FileId)
                        params.messageTest.value.success(res.Msg);
                    }).catch(err => {
                        console.log(err, 'err')
                    }).finally(() => {
                        params.uploadLock.value = false
                    })
                }
            }
            const previewBtn = h('img', { style: 'cursor:pointer;margin:0 4px;', onclick: () => { btnPreview(uid, type) }, src: "../Bussiness/img/svg/preview.svg", width: 20, height: 22 }, { default: () => '预览' })
            const downloadBtn = h('img', { style: 'cursor:pointer;margin:0 4px;', onclick: () => { btnDownLoad(uid, type) }, src: "../Bussiness/img/svg/download.svg", width: 20, height: 22 }, { default: () => '下载' })
            const deleteBtn = h('img', { style: 'cursor:pointer;margin:0 4px;', src: "../Bussiness/img/svg/delete.svg", width: 18, height: 22 }, { default: () => '删除' })
            const FDBtn = h(antd.Popconfirm, {
                title: "确定删除此文件？确定后不可恢复",
                onConfirm: () => btnDelete(data, type)

            }, { default: () => [deleteBtn] })
            var btns = h('div', { style: "display:flex;margin-left:10px" }, {
                default: () => [
                    isImageFile(data.file.url) ? previewBtn : null,
                    downloadBtn,
                    params.urlinfo.value.type == 9 ? null : FDBtn
                ]
            })
            return h('div', { style: 'margin-top:10px; width:400px;align-items:center; display:flex;justify-content:space-between' }, {
                default: () => [
                    data.file.name, btns
                ]
            })

        },
        IGetConfigList: (name) => {
            return new Promise((resolve, rej) => {
                Request({
                    url: "/SpecialDevice/GetConfigList",
                    method: 'post',
                    data: {
                        ConfigName: name
                    }
                }).then(res => {
                    console.log(res, 'res')
                    switch (name) {

                        case '设备状态':
                            params.eqstatusList.value = res.Data.map(e => ({
                                label: e.ConfigValue,
                                value: e.Id
                            }))
                            break;
                        case '设备种类':
                            params.eqtype1List.value = res.Data.map(e => ({
                                label: e.ConfigValue,
                                value: e.Id
                            }))
                            break;
                        case '设备类别':
                            params.eqtype2List.value = res.Data.map(e => ({
                                label: e.ConfigValue,
                                value: e.Id
                            }))
                            break;
                        case '设备品种':
                            params.eqtype3List.value = res.Data.map(e => ({
                                label: e.ConfigValue,
                                value: e.Id
                            }))
                            break;
                    }



                    resolve(res)
                }).catch(() => {
                    rej()
                })
            })

      
        },

        reset: () => {



        },
        IDeleteFile: (id) => {
 
            return new Promise((resolve,rej) => {
                Request({
                    url: "/SpecialDevice/DeleteSpecialFile",
                    method: 'post',
                    data: {
                        Id: id
                    }
                }).then(res => {

                    resolve(res)
                }).catch(() => {
                    rej()
                })
            })
     
        },
        toAdd: () => {
            params.popType.value = null
            methods.reset()
            params.formData.value = {

            }
            params.uploadImg.value.fileList =[]
            params.popShow.value = true
        },

        handleDetail : (item) => {
            params.popType.value = 9
            Request({
                url: "/SpecialDevice/GetSpecialDeviceDetail",
                method: 'post',
                data: {
                    Id: item.Id
                }
            }).then(res => {
                params.formData.value = res.Data
                params.formData.value.LastCheckTime = dayjs(dealTime(res.Data.LastCheckTime, 'YYYY-MM-DD'))
                params.formData.value.NextCheckTime = dayjs(dealTime(res.Data.NextCheckTime, 'YYYY-MM-DD'))
                params.uploadImg.value.fileList = res.Data.FileList.map(e => {
                    e.url = e.FilePath
                    e.name = e.FileName
                    e.old = true
                    return e
                })
                //params.formData.value = params.uploadImg.value.fileList.filter(e => e.FileSize).map(e => e.FileId)
                params.popShow.value = true
            })
        },

             handleEdit : (item) => {
            params.popType.value = 1
            Request({
                url: "/SpecialDevice/GetSpecialDeviceDetail",
                method: 'post',
                data: {
                    Id: item.Id
                }
            }).then(res => {
                params.formData.value = res.Data
                params.formData.value.LastCheckTime = dayjs(dealTime(res.Data.LastCheckTime, 'YYYY-MM-DD'))
                params.formData.value.NextCheckTime = dayjs(dealTime(res.Data.NextCheckTime, 'YYYY-MM-DD'))
                params.uploadImg.value.fileList = res.Data.FileList.map(e => {
                    e.url = e.FilePath
                    e.name = e.FileName
                    e.old = true
                    return e
                })
                params.popShow.value = true
            })
        },

       handleDelete : (item) => {
            Request({
                url: "/SpecialDevice/DeleteSpecialDeviceDetail",
                method: 'post',
                data: {
                    Id: item.Id
                }
            }).then(res => {
                params.messageTest.value.success(res.Msg);
                methods.getTableList(true)
            })

        },
        handleOk: () => {


       
            if (params.popType.value == 9) {
                return params.popShow.value = false
            }
            params.formData.value.FileList = params.uploadImg.value.fileList.filter(e => e.FileSize).map(e => e.FileId)
            if (params.popType.value == 1) {
                params.proxy.value.$refs.formRef
                    .validate()
                    .then(() => {
                        params.uploadLock.value = true
                        Request({
                            url: "/SpecialDevice/EditSpecialDevice",
                            method: 'post',
                            data: params.formData.value
                        }).then(res => {
                            params.messageTest.value.success(res.Msg);
                            params.popShow.value = false
                            methods.getTableList(true)
                        }).finally(() => {
                            params.uploadLock.value = false
                        })


                    })
                    .catch(error => {
                        console.log('error', error);
                    });
            } else {
                params.proxy.value.$refs.formRef
                    .validate()
                    .then(() => {
                        params.uploadLock.value = true
                        Request({
                            url: "/SpecialDevice/AddSpecialDevice",
                            method: 'post',
                            data: params.formData.value
                        }).then(res => {
                            params.messageTest.value.success(res.Msg);
                            params.popShow.value = false
                            methods.getTableList(true)

                        }).finally(() => {
                            params.uploadLock.value = false
                        })


                    })
                    .catch(error => {
                        console.log('error', error);
                    });
            }

 

        },
     



        handleTableChange: (page) => {
            const { current, pageSize } = page
            params.pagination.value.current = current;
            params.pagination.value.pageSize = pageSize;
            methods.getTableList()
        },

        getTableList: async (isRresh) => {
            if (isRresh) {
                params.pagination.value.current = 1
            }
            params.pagination.value.loading = true

            Request({
                url: "/SpecialDevice/GetSpecialDevicePageList",
                method: 'post',
                params: {
                    page: params.pagination.value.current,
                    pageSize: params.pagination.value.pageSize
                },
                data: {
                    ...params.queryParams.value,
       /*             TypeId: params.cIndex.value*/
                }
            }).then(res => {
                params.dataSource.value =res.Data.Data

                 params.pagination.value.total = res.Data?.TotalItemCount
            }).finally(() => {
                params.pagination.value.loading = false
            })

        },
        filterOption: (val, type) => {
            return `${type.label}`.includes(`${val || ''}`)
        },
 

        init: () => {
            getBrowserInfo().catch(err => { console.log(err) })
            if (proxy) {
                params.proxy.value = proxy
            }

            params.urlinfo.value = queryURLParams()
            const { message } = antd
            params.messageTest.value = message
            params.messageTest.value.config({
                top: `10vh`,
                duration: 7,
                maxCount: 1,
                rtl: true,
            });
            setTimeout(() => {
                let info = Storage.get('AccountInfo', true)
                params.uinfo.value = info
                Request({
                    url: "/Account/createJwtToken",
                    method: 'post',
                    data: {
                        "userName": info && info.UserNo
                    }
                }).then(async res => {
                    Storage.set('token', res.Data, true)
                    //methods.IGetTypeList()
                    //methods.IGetCertiTypeList()
                    methods.getDeptList()
                    methods.getTableList(true)
                    params.uploadLock.value=true
                    const promises = [methods.IGetConfigList("设备状态"), methods.IGetConfigList("设备种类"), methods.IGetConfigList("预警级别"), methods.IGetConfigList("设备类别"), methods.IGetConfigList("设备品种")];
                    Promise.allSettled(promises).then((results) => { 
                        if (results.filter(e => e.status == "fulfilled").length == results.length) {
                            console.log('未全部请求成功')
                        } else {
                            console.log('全部请求成功')
                        }

                    }).finally(() => {
                        params.uploadLock.value = false
                    });





                })
            }, 400)

        },
    }

    const template = {
        imageModel: previewCom(params, methods).imageModel,
        pdfPopModel: previewCom(params, methods).pdfPopModel,
    }
    return {
        ...params,
        ...methods,
        template
    }
}

export default Composition